package com.wanjl.springMvc.controller;

import com.wanjl.springMvc.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

/**
 * @author WanJl
 * @version 1.0
 * @title UserController
 * @description
 * @create 2024/11/10
 */
@Controller
public class UserController {

    /**
     * 传递普通参数
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/user/login")
    @ResponseBody
    //@RequestParam注解，关联前端传入的参数名和后端controller控制器方法的参数名。
    //defaultValue属性：默认参数值
    //required属性：是否必填，默认是true。
    public String login(@RequestParam(value = "uname",defaultValue = "默认参数",required = false) String username, @RequestParam("pwd") String password){
        System.out.println("用户名："+username);
        System.out.println("密码："+password);
        if (username.equals("admin") && password.equals("123456")){

            return "success";
        }
        return "error";
    }

    /**
     * 传递实体类参数
     * @param user
     * @return
     */
    @RequestMapping("/user/save")
    @ResponseBody
    public String save(User user){
        System.out.println(user);
        return "success";
    }

    /**
     * 前端向后端传递数组类型参数
     * @param likes
     * @return
     */
    @RequestMapping("/user/likes")
    @ResponseBody
    public String selectByArray(String[] likes){    //likes[0]=aaa
        System.out.println(Arrays.toString(likes));
        return "success";
    }

    @RequestMapping("/user/listParams")
    @ResponseBody
    public String listParams(@RequestParam List<String> list){
        list.forEach(System.out::println);
        return "success";
    }

    /**
     * 集合参数传递---JSON格式
     * 1、需要在SpringMVC配置类中开启JSON格式数据的自动转换@EnableWebMvc
     * 2、使用@RequestBody注解把前端传入的JSON数据映射成方法形参的对象
     * @param list
     * @return
     */
    @RequestMapping("/user/listParamForJson")
    @ResponseBody
    public String listParamForJson(@RequestBody List<String> list){
        list.forEach(System.out::println);
        return "success";
    }

    /**
     * JSON格式传递实体类对象参数
     * @param user
     * @return
     */
    @RequestMapping("/user/objectForJson")
    @ResponseBody
    public String ObjectForJson(@RequestBody User user){
        System.out.println(user);
        return "success";
    }


}
